<?php

namespace pmvc\mvc\ioc;

use pmvc\cache\Cache;

use pmvc\ioc\xml\ParseContext;

use pmvc\ioc\xml\XmlObjectFactory;
use pmvc\ioc\xml\Extension;
use pmvc\ioc\PropertyDescriptor;
use pmvc\ioc\ObjectDescriptor;

use pmvc\util\XMLUtil;

use DOMElement;
use Exception;

/**
 * Extension for setting up annotations filter mapping.
 *
 */
class AnnotationsFilterMappingExtension
	implements Extension {

	/**
	 * {@inheritDoc}
	 */
	public function process(DOMElement $element, ParseContext $pc) {

		// are we reading frmo a file?
		$file = XMLUtil::getAttributeValue($element, "file");

		// setup autowire descriptor registrar
		if (isset($file)) {

			// get other params
			$useCache 	= XMLUtil::getAttributeValue($element, "useCache", "false");
			$ttl		= XMLUtil::getAttributeValue($element, "ttl", Cache::ONE_HOUR);
			$cacheIdRef	= XMLUtil::getAttributeValue($element, "cache");
			
			// generate id
			$id = uniqid('', true) . '#AutowireDescriptorRegistrar';
					
			// create descriptor for provider
			$providerId = $id."::FileAutowireCandidateProvider";
			$providerDesc = new ObjectDescriptor(
				$providerId, 'pmvc\ioc\annotation\FileAutowireCandidateProvider', $providerId);
			$providerDesc->properties []= new PropertyDescriptor("fileName", $file, PropertyDescriptor::TYPE_STRING);
			$providerDesc->properties []= new PropertyDescriptor("relativeFileName", $pc->getXmlFile(), PropertyDescriptor::TYPE_STRING);
			$providerDesc->properties []= new PropertyDescriptor("useCache", $useCache, PropertyDescriptor::TYPE_BOOLEAN);
			$providerDesc->properties []= new PropertyDescriptor("ttl", $ttl, PropertyDescriptor::TYPE_INTEGER);
			if (isset($cacheIdRef)) {
				$providerDesc->properties []= new PropertyDescriptor("cache", $cacheIdRef, PropertyDescriptor::TYPE_REF);
			}
			
			// create descritor
			$descriptor = new ObjectDescriptor(
			$id, 'pmvc\ioc\annotation\AutowireDescriptorRegistrar', $id);
				$descriptor->properties []= new PropertyDescriptor("provider", $providerId, PropertyDescriptor::TYPE_REF);
			
			// add it
			$pc->getObjectFactory()->addObjectDescriptor($providerDesc);
			$pc->getObjectFactory()->addObjectDescriptor($descriptor);
		}

		// add mapping
		$pc->getObjectFactory()->addObjectDescriptor(
			new ObjectDescriptor(uniqid('', true) . '#AnnotationsRequestFilterMapping',
			'pmvc\mvc\annotation\AnnotationsRequestFilterMapping'));
	}
}